<template>
  <div id="spaceDetailPage">
    <!-- 空间信息 -->
    <a-flex justify="space-between">
      <h2>{{ space.spaceName }}（{{ SPACE_TYPE_MAP[space.spaceType] }}）</h2>
      <a-space size="middle">
        <a-button
          v-if="canUploadPicture"
          type="primary"
          :href="`/add_picture?spaceId=${id}`"
          target="_blank"
        >
          + 创建图片
        </a-button>
        <a-button v-if="canEditPicture" :icon="h(EditOutlined)" @click="doBatchEdit">
          批量编辑</a-button
        >
        <a-button
          v-if="canManageSpaceUser && SPACE_TYPE_ENUM.TEAM === space.spaceType"
          type="primary"
          ghost
          :icon="h(TeamOutlined)"
          :href="`/spaceUserManage/${id}`"
          target="_blank"
        >
          成员管理
        </a-button>
        <a-button
          v-if="canManageSpaceUser"
          type="primary"
          ghost
          :icon="h(BarChartOutlined)"
          :href="`/space_analyze?spaceId=${id}`"
          target="_blank"
        >
          空间分析
        </a-button>

        <a-tooltip
          :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`"
        >
          <!--                    :percent="((space.totalSize * 100) / space.maxSize).toFixed(1)"-->
          <a-progress
            type="circle"
            :size="42"
            :percent="Number(((space.totalSize / space.maxSize) * 100).toFixed(1))"
          />
        </a-tooltip>
      </a-space>
    </a-flex>
    <div style="margin-bottom: 16px"></div>
    <PictureSearchForm :on-search="onSearch"></PictureSearchForm>

    <!-- 按颜色搜索 -->
    <a-form-item label="按颜色搜索" style="margin-top: 16px">
      <color-picker format="hex" @pureColorChange="onColorChange" />
    </a-form-item>

    <!-- 图片列表 新的调整使用图片列表组件,并补充分页组件-->
    <PictureList
      :dataList="dataList"
      :loading="loading"
      show-op
      :canEdit="canEditPicture"
      :canDelete="canDeletePicture"
      :onReload="searchList"
    />
    <!-- 分页组件-->
    <a-pagination
      v-if="shouldShowPagination"
      v-model:current="searchQueryParams.pageNum"
      v-model:page-size="searchQueryParams.pageSize"
      :total="total"
      responsive
      show-size-changer
      show-quick-jumper
      :page-size-options="pageSizeOptions"
      :show-total="(total) => `共 ${total} 条记录`"
      @change="onPageChange"
      style="text-align: right"
    >
      <template #buildOptionText="props">
        <span class="custom-option-text">{{ props.value }}条/页</span>
      </template>
    </a-pagination>

    <BatchEditPictureModal
      ref="batchEditPictureModalRef"
      :spaceId="id"
      :pictureList="dataList"
      :onSuccess="onBatchEditPictureSuccess"
    ></BatchEditPictureModal>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'
import { formatSize } from '@/utils/index.ts'
import { message } from 'ant-design-vue'
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController.ts'
import PictureList from '@/components/PictureList.vue'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { BarChartOutlined, EditOutlined, TeamOutlined } from '@ant-design/icons-vue'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { SPACE_PERMISSION_ENUM, SPACE_TYPE_ENUM, SPACE_TYPE_MAP } from '../../constants/space.ts'

const route = useRoute()
const loading = ref(false)
const error = ref<string | null>(null)
const space = ref<API.SpaceVO>({})
const props = defineProps<{
  id: string | number
}>()

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE) // 管理空间用户权限
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD) // 上传图片权限
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT) // 编辑图片权限
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE) // 删除图片权限

// 获取空间信息
const getSpaceInfo = async () => {
  try {
    const response = await getSpaceVoByIdUsingGet({ id: props.id })
    // debugger
    if (response.code === 0 && response.data) {
      space.value = response.data
    } else {
      throw new Error(response.message || '获取空间详情失败')
    }
  } catch (err) {
    error.value = err.message
  } finally {
    loading.value = false
  }
}
/**
 * 初始化加载图片信息
 */
onMounted(() => {
  getSpaceInfo()
})

const pageSizeOptions = ref<string[]>(['10', '20', '30', '40', '50'])
const dataList = ref([])
const total = ref(0)

// 计算属性：判断是否需要显示分页器
const shouldShowPagination = computed(() => {
  // 如果 dataList 为空或长度小于分页大小（例如 pageSize），则将分页器隐藏或设置为不可见。
  return (
    dataList.value.length >= searchQueryParams.pageSize && total.value > searchQueryParams.pageSize
  )
})
const onPageChange = (pageNum: number, pageSize: number) => {
  searchQueryParams.pageNum = pageNum
  searchQueryParams.pageSize = pageSize
  searchList()
}

// 定义查询参数对象，用于分页及搜索条件传递给后端接口
const searchQueryParams = reactive<API.PictureQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 查询用户列表：根据当前的查询参数向后端请求用户数据
const searchList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const params = {
      spaceId: props.id,
      ...searchQueryParams,
    }
    const res = await listPictureVoByPageUsingPost(params)
    if (res.code === 0 && res.data) {
      dataList.value = res.data.records
      total.value = Number(res.data.total)
    }
  } catch (e) {
    message.error('加载图片失败，' + e.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  searchList()
})

// 搜索图片事件
const onSearch = (values: API.PictureQueryRequest) => {
  searchQueryParams.pageNum = 1
  searchQueryParams.pageSize = 10
  searchQueryParams.searchText = values.searchText
  searchQueryParams.category = values.category
  searchQueryParams.tags = values.tags
  searchQueryParams.name = values.name
  searchQueryParams.introduction = values.introduction
  searchQueryParams.picWidth = values.picWidth
  searchQueryParams.picHeight = values.picHeight
  searchQueryParams.picFormat = values.picFormat
  searchQueryParams.startEditTime = values.startEditTime
  searchQueryParams.endEditTime = values.endEditTime
  searchList()
}

// 切换颜色事件
const onColorChange = async (color: string) => {
  const res = await searchPictureByColorUsingPost({
    picColor: color,
    spaceId: props.id,
  })
  if (res.code === 0 && res.data) {
    const data = res.data ?? []
    dataList.value = data
    total.value = data.length
  } else {
    message.error('获取数据失败，' + res.message)
  }
}

// 分享弹窗引用
const batchEditPictureModalRef = ref()

// 批量编辑成功后，刷新数据
const onBatchEditPictureSuccess = () => {
  searchList()
}

// 打开批量编辑弹窗
const doBatchEdit = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}

watch(
  () => props.id,
  (newSpaceId) => {
    getSpaceInfo()
    searchList()
  },
)
</script>

<style scoped>
/* Your styles here */
</style>
